<template>
  <div class="plugin-manager">
    <NavMenu />
    <div class="main-content">
      <!-- 顶部导航栏 -->
      <div class="top-navbar">
        <div>
          <h1 class="page-title">插件管理</h1>
        </div>
        
        <div class="navbar-actions">
          <div class="search-box">
            <el-input 
              v-model="searchQuery" 
              placeholder="搜索插件..." 
              :prefix-icon="Search"
              class="search-input"
              @input="handleSearch"
            />
          </div>
          
          <el-button 
            type="primary" 
            @click="uploadDialogVisible = true" 
            class="upload-btn"
          >
            <el-icon><Upload /></el-icon>
            上传插件
          </el-button>
          
          <el-dropdown 
            @command="handleCommand" 
            trigger="click"
          >
            <div class="avatar-container">
              <el-avatar :size="36" :icon="UserFilled" />
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <div class="dropdown-header">
                  <span>{{ username }}</span>
                </div>
                <el-dropdown-item command="logout">
                  <el-icon><SwitchButton /></el-icon>
                  退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
      
      <!-- 页签导航 -->
      <div class="tabs-container">
        <el-tabs v-model="activeTab" @tab-change="handleTabChange" class="custom-tabs">
          <el-tab-pane label="全部插件" name="all">
            <template #label>
              <el-icon><Grid /></el-icon>
              <span>全部插件</span>
            </template>
          </el-tab-pane>
          <el-tab-pane label="已启用" name="enabled">
            <template #label>
              <el-icon><Select /></el-icon>
              <span>已启用</span>
            </template>
          </el-tab-pane>
          <el-tab-pane label="已禁用" name="disabled">
            <template #label>
              <el-icon><Close /></el-icon>
              <span>已禁用</span>
            </template>
          </el-tab-pane>
        </el-tabs>
      </div>
      
      <!-- 内容区域 -->
      <div class="plugin-content">
        <el-row :gutter="20">
          <el-col 
            v-for="plugin in paginatedPlugins" 
            :key="plugin.id" 
            :xs="24" 
            :sm="12" 
            :md="8" 
            :lg="8"
            class="plugin-col"
          >
            <PluginCard 
              :plugin="plugin" 
              @view-detail="showPluginDetail" 
              @toggle-status="togglePluginStatus" 
              @delete-plugin="deletePluginHandler" 
            />
          </el-col>
        </el-row>
        
        <!-- 分页 -->
        <el-pagination
          v-if="totalItems > pageSize"
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="totalItems"
          layout="prev, pager, next"
          class="pagination"
          background
          @current-change="handlePageChange"
        />
      </div>
    </div>
    
    <!-- 上传插件对话框 -->
    <UploadPluginDialog 
      v-model:visible="uploadDialogVisible" 
      @upload-success="handleUploadSuccess" 
    />
    
    <!-- 插件详情对话框 -->
    <PluginDetailDialog 
      v-model:visible="detailDialogVisible" 
      :plugin="selectedPlugin" 
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, 
  Upload, 
  User as UserFilled, 
  SwitchButton, 
  Grid, 
  Select, 
  CircleClose as Close 
} from '@element-plus/icons-vue'

import NavMenu from '@/components/layout/NavMenu.vue'
import PluginCard from '@/components/plugin/PluginCard.vue'
import UploadPluginDialog from '@/components/plugin/UploadPluginDialog.vue'
import PluginDetailDialog from '@/components/plugin/PluginDetailDialog.vue'
import { getPluginList, updatePluginStatus, deletePlugin, getPluginDetail, type PluginDetail, type PluginStatus } from '@/api/plugin'

const router = useRouter()

// 用户信息
const username = ref('用户名')

// 搜索状态
const searchQuery = ref('')

// 页签状态
const activeTab = ref<'all' | 'enabled' | 'disabled'>('all')

// 分页状态
const currentPage = ref(1)
const pageSize = ref(100)
const totalItems = ref(0)

// 插件列表
const plugins = ref<PluginDetail[]>([])

// 对话框状态
const uploadDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const selectedPlugin = ref<PluginDetail | null>(null)

// 获取过滤后的插件列表
const filteredPlugins = computed(() => {
  try {
    let result = plugins.value
    
    // 根据标签筛选
    if (activeTab.value === 'enabled') {
      result = result.filter(plugin => plugin.status === 'enabled')
    } else if (activeTab.value === 'disabled') {
      result = result.filter(plugin => plugin.status === 'disabled')
    }
    
    // 根据搜索关键词筛选
    if (searchQuery.value) {
      const query = searchQuery.value.toLowerCase()
      result = result.filter(plugin => 
        plugin.name.toLowerCase().includes(query) || 
        plugin.developer.toLowerCase().includes(query) ||
        plugin.description.toLowerCase().includes(query)
      )
    }
    
    totalItems.value = result.length
    
    // 分页处理
    const startIndex = (currentPage.value - 1) * pageSize.value
    return result.slice(startIndex, startIndex + pageSize.value)
  } catch (error) {
    console.error('处理插件数据错误:', error)
    return []
  }
})

// 获取当前页的插件
const paginatedPlugins = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value
  return filteredPlugins.value.slice(startIndex, endIndex)
})

// 处理标签切换
const handleTabChange = (tab: 'all' | 'enabled' | 'disabled') => {
  activeTab.value = tab
  currentPage.value = 1
  fetchPlugins()
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchPlugins()
}

// 处理翻页
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchPlugins()
}

// 显示插件详情
const showPluginDetail = async (plugin: PluginDetail) => {
  try {
    // 获取插件详情
    const detailData = await getPluginDetail(plugin.id)
    selectedPlugin.value = detailData
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取插件详情失败:', error)
    ElMessage.error(`获取插件详情失败：${error instanceof Error ? error.message : String(error)}`)
  }
}

// 切换插件状态
const togglePluginStatus = async (plugin: PluginDetail) => {
  try {
    const newStatus: PluginStatus = plugin.status === 'enabled' ? 'disabled' : 'enabled'
    await updatePluginStatus(plugin.id, newStatus)
    ElMessage.success(`插件已${newStatus === 'enabled' ? '启用' : '禁用'}`)
    await fetchPlugins()
  } catch (error) {
    console.error('切换插件状态失败:', error)
    ElMessage.error(`切换插件状态失败：${error instanceof Error ? error.message : String(error)}`)
  }
}

// 删除插件
const deletePluginHandler = async (plugin: PluginDetail) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除此插件吗？此操作不可恢复。`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    await deletePlugin(plugin.id)
    ElMessage.success('插件删除成功')
    await fetchPlugins()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`删除失败：${error instanceof Error ? error.message : String(error)}`)
    }
  }
}

// 获取插件列表
const fetchPlugins = async () => {
  try {
    const response = await getPluginList({
      pageRequest: {
        currentPage: currentPage.value,
        pageSize: pageSize.value,
        offset: 0
      },
      status: activeTab.value === 'all' ? 'all' : activeTab.value,
      keyword: searchQuery.value || undefined
    })
    
    // 检查响应数据结构
    console.log('Plugin List Response:', response)
    
    // 直接使用返回的数据
    plugins.value = response.records || []
    totalItems.value = response.totalRecords || 0
  } catch (error) {
    console.error('获取插件列表失败:', error)
    ElMessage.error(`获取插件列表失败：${error instanceof Error ? error.message : String(error)}`)
  }
}

// 处理上传成功
const handleUploadSuccess = () => {
  ElMessage.success('插件上传成功！')
  uploadDialogVisible.value = false
  fetchPlugins()
}

// 处理用户操作
const handleCommand = (command: string) => {
  if (command === 'logout') {
    try {
      console.log('开始登出操作')
      // 清除用户信息
      localStorage.removeItem('isLoggedIn')
      localStorage.removeItem('token')
      localStorage.removeItem('username')
      
      // 跳转到登录页
      router.push({ path: '/login', replace: true })
      
      ElMessage.success('已成功退出登录')
    } catch (error) {
      console.error('登出失败:', error)
      ElMessage.error('登出时发生错误')
    }
  }
}

// 加载插件数据
onMounted(async () => {
  try {
    console.log('开始获取插件数据')
    await fetchPlugins()
    console.log('获取插件数据成功:', plugins.value.length)
    
    // 获取用户信息
    const storedUsername = localStorage.getItem('username')
    if (storedUsername) {
      username.value = storedUsername
    }
  } catch (error) {
    console.error('获取插件列表失败:', error)
    ElMessage.error(`获取插件列表失败：${error instanceof Error ? error.message : String(error)}`)
  }
})

// 监听筛选条件变化，重新获取插件列表
watch([activeTab, searchQuery, currentPage], () => {
  fetchPlugins()
})
</script>

<style scoped>
.plugin-manager {
  display: flex;
  height: 100vh;
  background-color: #f8f9fa;
}

.main-content {
  flex: 1;
  overflow-y: auto;
  padding: 0 20px;
}

.top-navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #eee;
  background-color: white;
  height: 70px;
  padding: 0 20px;
  margin: 0 -20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.navbar-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.search-box {
  width: 240px;
}

.search-input :deep(.el-input__wrapper) {
  border-radius: 12px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.upload-btn {
  background: linear-gradient(135deg, #ffb74d 0%, #ffa726 100%);
  border: none;
  border-radius: 12px;
  padding: 10px 20px;
  font-weight: 500;
  box-shadow: 0 2px 6px rgba(255, 183, 77, 0.4);
}

.avatar-container {
  cursor: pointer;
  border-radius: 50%;
  overflow: hidden;
  background-color: #f0f0f0;
}

.dropdown-header {
  padding: 8px 16px;
  border-bottom: 1px solid #eee;
  font-weight: 500;
}

.tabs-container {
  margin: 20px 0;
  border-bottom: 1px solid #eee;
}

.custom-tabs {
  margin-bottom: -1px;
}

.plugin-content {
  padding: 24px 0;
}

.plugin-col {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}

/* 覆盖Element Plus样式 */
:deep(.el-tabs__item) {
  padding: 0 20px;
  height: 50px;
  line-height: 50px;
  font-size: 16px;
}

:deep(.el-tabs__item.is-active) {
  color: #ffb74d;
  font-weight: 500;
}

:deep(.el-tabs__item:hover) {
  color: #ffa726;
}

:deep(.el-tabs__active-bar) {
  background-color: #ffb74d;
  height: 3px;
}

:deep(.el-tabs__nav-wrap::after) {
  height: 1px;
}

:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #ffb74d;
  border-radius: 12px;
}

:deep(.el-pagination.is-background .el-pager li:not(.is-disabled)) {
  border-radius: 12px;
}

:deep(.el-pagination.is-background .el-pager li:not(.is-disabled):hover) {
  color: #ffb74d;
}

:deep(.el-pagination__prev, .el-pagination__next) {
  border-radius: 12px;
}

:deep(.el-dropdown-menu) {
  border-radius: 12px;
  overflow: hidden;
}

:deep(.el-dialog) {
  border-radius: 12px;
  overflow: hidden;
}
</style> 